import React, { useState, useRef, useEffect, forwardRef } from 'react';
import styles from './index.less';
import classnames from 'classnames';

interface INSelectProps {
    type?: 'light' | 'dark' | 'default'; //选择框样式类型
    onChange?: (value: any) => void; // onchenge事件
    onClick?: () => void;
    appendBefore?: React.ReactNode; // 按钮前缀
    children?: React.ReactNode; // 子元素
    value?: number | string; // 属性值
    width?: string;
}

interface INSelectItem {
    index: number | string | null; // 索引
    value: number | string; // 值
    title: string | number | React.ReactNode; // 选中展示项
}

const Select = forwardRef((props: INSelectProps, _ref) => {
    const { onChange, onClick, appendBefore, type, children, value, width } = props;

    const [visible, setVisible] = useState(false);
    const [currentItem, setCurrentItem] = useState<INSelectItem>({ index: null } as INSelectItem);
    const selectbtn = useRef<any | null>(null);


    // 选中弹出下拉
    const clickselect = () => {
        setVisible(true);
        onClick && onClick();
    };

    // option点击项
    const onclick = (index: number, item: any) => {
        setVisible(false);
        setCurrentItem({ index: index, title: item, value: item.props.value });
        onChange && onChange(item.props.value);
    };

    // 初始化
    useEffect(() => {
        let currentItem = {} as INSelectItem;
        children &&
            React.Children.map(children, (element: any, index: number) => {
                if (element?.props?.value === value) {
                    currentItem.index = index;
                    currentItem.value = element.props.value;
                    currentItem.title = element.props.title || element;
                }
                return;
            });
        setCurrentItem(currentItem);
    }, [children]);

    // 按钮选项
    useEffect(() => {
        window.addEventListener('click', onClickOutsideHandler);
        return () => {
            window.removeEventListener('click', onClickOutsideHandler);
        };
    });
    const onClickOutsideHandler = (event: any) => {
        visible && !selectbtn.current.contains(event.target) && setVisible(false);
    }


    // 样式表
    const classes = classnames(styles['nselect-content'], {
        [`${styles[`nselect-content-${type}`]}`]: type,
    });
    const check_item_index = (index: number) => index === currentItem.index && styles['active'];

    const handleClose = () => setVisible(false);

    return (
        <div className={classes} ref={selectbtn}>
            <div className={styles['nselect-title']} onClick={clickselect} style={{ width: width }}>
                {appendBefore && <div className={styles['nselect-append']}>{appendBefore}</div>}
                {currentItem.title || <div />}
                <span
                    className="iconfont iconxiajiantou"
                    style={{ fontSize: '18px', color: '#272636', marginLeft: '10px', cursor: 'pointer' }}
                />
            </div>
            <div className={classnames(styles['nselect-options'], !visible && styles['nselect-show'])} style={{ width: width }}>
                <div className={styles['nselect-select']} onClick={handleClose}>
                    {currentItem.title || <div />}
                    <span
                        className="iconfont iconxiajiantou"
                        style={{ fontSize: '18px', color: '#272636', marginLeft: '10px', cursor: 'pointer' }}
                    />
                </div>
                <div className={`${styles['nselect-select-box']} scroll-bar`}>
                    {React.Children.map(children, (element: any, index) =>
                        element && (
                            <div
                                key={element && element.props.value}
                                className={classnames(styles['nselect-item'], check_item_index(index))}
                                onClick={() => onclick(index, element)}
                            >
                                {element}
                            </div>
                        )
                    )}
                </div>
            </div>
        </div>
    );
});

Select.defaultProps = {
    type: 'default',
    width: '150px',
};

export default Select;
